package util;

import java.io.*;
import java.time.LocalDate;
import java.util.UUID;

/**
 * @classname:FileUtil
 * @description:
 * @author: Mr.Z
 * @date: 2020/12/29 23:32
 * @version: 0.1
 * @since:1.8
 */
public class FileUtil {
    private FileUtil() {
    }

    private static final String TARGET_DIRECTORY = "upload/user/";

    public static String fileUpload(String sourceFilePath) {

        String data = LocalDate.now().toString();
        String pictureName = sourceFilePath.substring(sourceFilePath.lastIndexOf(File.separatorChar) + 1);
        File childDirectory = new File(TARGET_DIRECTORY, data);

        if (!childDirectory.exists()) {
            childDirectory.mkdirs();
        }
        String uuidStr = UUID.randomUUID().toString().replaceAll("-", "");
        String fileName = uuidStr +"-"+pictureName;
        File targetFilePath = new File(childDirectory, fileName);
        String path = "";
        try (
                BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(sourceFilePath));
                BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(targetFilePath));
        ) {
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = bufferedInputStream.read(bytes)) != -1) {
                bufferedOutputStream.write(bytes, 0, len);
            }
            path = targetFilePath.getPath();
            System.out.println("文件上传成功 " + path);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }
}
